<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\model\FollowModel;
use app\model\UsersModel;
use app\common\service\Message;

class User extends BaseApi
{
    protected ?string $dataModel = UsersModel::class;
    protected array $allowSearch = ['nickname', 'username', 'email', 'phone', 'status'];

    /**
     * @notes 通过用户ID获取个人信息
     */
    public function infoByUserId()
    {
        $userId = input("user_id");
        $loginUserId = $this->getUserId();

        $user = UsersModel::find($userId);
        $user["is_follow"] = FollowModel::where('user_id', $loginUserId)->where('follow_uid', $userId)->exists() ? 1 : 0;

        if (!$user) {
            return $this->fail('用户不存在');
        }

        return $this->success($user);
    }

    /**
     * @notes 获取当前登录人信息
     */
    public function getInfo()
    {
        $userId = $this->getUserId(true);

        $user = UsersModel::find($userId);

        if (!$user) {
            return $this->fail('用户不存在');
        }

        $user->makeHidden(['openid', 'unionid']);

        return $this->success($user);
    }

    public function setInfo()
    {
        // 获取当前用户ID
        $userId = $this->getUserId(true);
        
        // 获取参数
        $field = input('field');
        $value = input('value');
        
        // 参数验证
        if (empty($field)) {
            return $this->fail('字段名不能为空');
        }
        
        if ($value === null || $value === '') {
            return $this->fail('字段值不能为空');
        }
        
        // 定义允许修改的字段白名单
        $allowedFields = [
            'nickname',
            'avatar', 
            'email',
            'gender',
            'birthday',
            'intro'
        ];
        
        // 检查字段是否在白名单中
        if (!in_array($field, $allowedFields)) {
            return $this->fail('不允许修改该字段');
        }
        
        // 字段值验证
        $validationRules = [
            'nickname' => function($val) {
                return mb_strlen($val) >= 2 && mb_strlen($val) <= 20;
            },
            'email' => function($val) {
                return filter_var($val, FILTER_VALIDATE_EMAIL);
            },
            'gender' => function($val) {
                return in_array($val, [0, 1, 2]); // 0:未知, 1:男, 2:女
            },
            'birthday' => function($val) {
                return preg_match('/^\d{4}-\d{2}-\d{2}$/', $val) && strtotime($val);
            }
        ];
        
        // 执行字段验证
        if (isset($validationRules[$field])) {
            if (!$validationRules[$field]($value)) {
                $errorMessages = [
                    'nickname' => '昵称长度必须在2-20个字符之间',
                    'email' => '邮箱格式不正确',
                    'gender' => '性别值无效',
                    'birthday' => '生日格式不正确，请使用YYYY-MM-DD格式'
                ];
                return $this->fail($errorMessages[$field] ?? '字段值格式不正确');
            }
        }
        
        try {
            // 更新用户信息
            $user = UsersModel::find($userId);
            if (!$user) {
                return $this->fail('用户不存在');
            }
            
            $user->$field = $value;
            $user->save();
            
            return $this->success([
                'field' => $field,
                'value' => $value
            ]);
        } catch (\Exception $e) {
            return $this->fail('修改失败，请稍后重试');
        }
    }

    /**
     * @notes 更新用户头像，昵称，性别
     */
    public function updateUser()
    {
        $params = (new UserValidate())->post()->goCheck("updateUser");

        UsersModel::where('id', $this->getUserId())->update([
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'avatar' => $params['avatar']
        ]);

        return $this->success('操作成功');
    }

    //登录用户粉丝列表
    public function userFans()
    {
        $userId = $this->getUserId();
        $followUids = FollowModel::where('follow_uid', $userId)->pluck('user_id');

        $paginate = UsersModel::whereIn('id', $followUids)->paginate(10);

        $list = $paginate->items();

        foreach ($list as &$item) {
            $item['is_follow'] = FollowModel::where('user_id', $userId)->where('follow_uid', $item['id'])->exists() ? 1 : 0;
        }

        return $this->dataByPage($paginate);
    }

    //登录用户关注列表
    public function follow()
    {
        $userId = $this->getUserId();
        $followUids = FollowModel::where('user_id', $userId)->pluck('follow_uid');

        $paginate = UsersModel::whereIn('id', $followUids)->paginate(10);

        $list = $paginate->items();

        foreach ($list as &$item) {
            $item['is_follow'] = FollowModel::where('user_id', $item['id'])->where('follow_uid', $userId)->exists() ? 1 : 0;
        }

        return $this->dataByPage($paginate);
    }


    //添加关注
    public function addFollow()
    {
        $followUserId = input("user_id");
        $loginUserId = $this->getUserId();

        if ($followUserId == $loginUserId) {
            return $this->fail("不能关注自己");
        }

        $exists = FollowModel::where('user_id', $loginUserId)->where('follow_uid', $followUserId)->exists();

        if ($exists) {
            return $this->fail("您已关注过该用户");
        }

        $result = FollowModel::create([
            'user_id' => $loginUserId,
            'follow_uid' => $followUserId,
        ]);

        $nickname = UsersModel::where('id', $loginUserId)->value('nickname');

        if ($result) {
            UsersModel::where('id', $loginUserId)->increment('follow_num');
            UsersModel::where('id', $followUserId)->increment('fans_num');
            Message::send($loginUserId, $followUserId, 0, 4, "【" . $nickname . "】关注了你");
            return $this->success("关注成功");
        }

        return $this->fail("关注失败");
    }

    //取消关注
    public function cancelFollow()
    {
        $followUserId = input("user_id");
        $loginUserId = $this->getUserId();

        $follow = FollowModel::where('user_id', $loginUserId)->where('follow_uid', $followUserId)->first();

        if (!$follow) {
            return $this->fail("未关注该用户");
        }

        $result = $follow->delete();
        if ($result) {
            UsersModel::where('id', $loginUserId)->decrement('follow_num');
            UsersModel::where('id', $followUserId)->decrement('fans_num');
            return $this->success("已取消关注");
        }
        return $this->fail("错误");
    }

    //搜索
    public function search()
    {
        $keyword = input("keyword");
        $paginate = UsersModel::where('nickname', 'like', "%$keyword%")->paginate(10);
        return $this->dataByPage($paginate);
    }
}